/**
 * Created by chengming on 18/5/24.
 * version 1.0
 * 人民网
 */
const ArticleHrefAdapter = require('../ArticleHrefAdapter');
const request = require('request-promise');
const vm = require('vm');
const cheerio = require('cheerio');
const urlTool = require('url');
const logger = require('../../conf/logger');

module.exports = class Pbc extends ArticleHrefAdapter{

	resetWinEnv(){
        if(global.window){
            delete global.window;
        }

        if(global.document){
            delete global.document;
        }
	}

	initWinEnv(){

		global.window = {
			innerWidth:1232,
			innerHeight:632,
			screenX:11,
			screenY:22,
			screen:{
				width:1280,
				height:800
			}
		};

		global.document = {
			documentElement:{
				clientWidth:1217,
				clientHeight:550
			},
			body:{
				clientWidth:1217,
				clientHeight:1467
			},
			_cookie: [],

			get cookie(){
				return this._cookie;
			},

			set cookie(val){
				this._cookie.push(val);
			}
		};
	}

	async doRequest(){

		//初始化窗口属性
		this.resetWinEnv();
		this.initWinEnv();

		//创建全局cookie
		var jar = request.jar();

        /*let ip = await request("http://api.ip.data5u.com/dynamic/get.html?order=49a00b94b07e56dfbaac056189cb8dca&sep=3");
        let proxy="http://"+ip;*/
		
		//使用cookie
		const jsbody = await request({
			jar:jar,
			url: this.requestUrl,
			headers:{
				'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',
			}
		});

		let $ = cheerio.load(jsbody);
		let realLink = $('script').html();

        let vmData = vm.runInThisContext(realLink);

		let newUrl = urlTool.resolve(this.requestUrl, window.location);

		console.log("解析后的新url为："+newUrl);

		for(let cookieStr of document.cookie){
			let cookie = request.cookie(cookieStr);
			jar.setCookie(cookie, this.requestUrl);
		}

		this.resetWinEnv();

        let options = {
				jar:jar,
				url:newUrl,
				headers:{
					'Referer':this.requestUrl,
					'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',
				},
            encoding:null
        };

        logger.debug(this.pageName +" 的请求头信息为" + JSON.stringify(options));

		return await request(options);
	}
}